#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

#include "PoolJob.h"
//#include "parser.h"
#include "Communicator.h"

//#include "dumpcode.h"


CPoolJobHttpProxy::CPoolJobHttpProxy() 
{
	memset(&m_enginedata, 0, sizeof(m_enginedata));
}

CPoolJobHttpProxy::CPoolJobHttpProxy( CPoolJobHttpProxy &job )
{
	m_enginedata = job.m_enginedata;
}

ENGINE_DATA CPoolJobHttpProxy::GetEngineData()
{
	return m_enginedata;
}

void CPoolJobHttpProxy::SetEngineData(ENGINE_DATA ed)
{
	m_enginedata = ed;
}

/*
 * Job function to be used by the thread pool
 */
unsigned CPoolJobHttpProxy::RunningJob()
{
	CHttpCommunicator	httpComm;

	
	/* a connection information is passed to the CCommunicator for http proxy.
		m_httpProxyData should have address information of three hosts(client, proxy) and socket number
		between client and proxy. */

	httpComm.SetHttpProxyData(&(m_enginedata.HttpProxyData));

	if(m_enginedata.ProxyInfo.mode == PM_NONCONTROL) {
		/* receive a request from client. content is stored in httpComm instance. */
		if(httpComm.GetCommunicateState() == CS_READY_TO_RECV_REQ) {
			if(!httpComm.readProxyHttpRequest())
				return 1;
		} else
			return 1;

		/* send a request to web server. */
		if(httpComm.GetCommunicateState() == CS_READY_TO_SEND_REQ) {
			if(!httpComm.sendProxyHttpRequest())
				return 1;
		} else 
			return 1;

		/* receive a response from web server */
		if(httpComm.GetCommunicateState() == CS_READY_TO_RECV_RES) {
			if(!httpComm.readProxyHttpResponse())
				return 1;
		} else 
			return 1;

		/* send a response to client. */
		if(httpComm.GetCommunicateState() == CS_READY_TO_SEND_RES) {
			if(!httpComm.sendProxyHttpResponse())
				return 1;
		} else 
			return 1;
	}

		
	httpComm.CleanupHttpComm();

	return 0;
}

CPoolJobHttpProxy& CPoolJobHttpProxy::operator =(const CPoolJobHttpProxy &job)
{
	m_enginedata = job.m_enginedata;

	return *this;
}





//////////// TEST /////////////////////////////////////

//definition of the copy constructor
CPoolJobTest::CPoolJobTest(CPoolJobTest &job)
{
	m_clientSock = job.m_clientSock;
}

// main working function used by a thread
unsigned CPoolJobTest::RunningJob()
{
	int ret=0;
	char buf[1024]={0};

	while(1) {
		ret = recv(m_clientSock, buf, 1024, 0);
		if( 0 >= ret )
			break;

		printf("message: %s\n", buf);
	}

	closesocket(m_clientSock);

	return 0;
}

void CPoolJobTest::SetClientSock(SOCKET sock)
{
	m_clientSock = sock;
}


// operator overload
CPoolJobTest& CPoolJobTest::operator =(const CPoolJobTest &job)
{
	m_clientSock = job.m_clientSock;

	return *this;
}
